package com.top145;

import java.util.HashMap;

public class Solution166 {
    public String fractionToDecimal(int numerator, int denominator) {
        long a = (long) numerator;
        long b = (long) denominator;
        if (a % b == 0) return String.valueOf(a / b);
        StringBuffer sb = new StringBuffer();
        if (a * b < 0) sb.append('-');
        a = Math.abs(a);
        b = Math.abs(b);
        sb.append(a / b).append('.');
        a %= b;
        HashMap<Long, Integer> map = new HashMap<>();
        while (a != 0) {
            map.put(a, sb.length());
            a *= 10;
            sb.append(a / b);
            a %= b;
            if (map.containsKey(a)) {
                Integer integer = map.get(a);
                return sb.substring(0, integer) + "(" + sb.substring(integer) + ")";
            }
        }
        return sb.toString();
    }
}
